﻿using System.Collections.Generic;
using System.Linq;
using NHibernate;
using SOLInfo.GEN.Domain.Entities;

namespace SOLInfo.GEN.Repository
{
    public class NoticiaRepository:RepositoryBase<Noticia>, IRepository<Noticia>
    {
        public NoticiaRepository(ISession session) : base(session) { }

        public IList<Noticia> ListarResultadoBuscaNoticia(IList<Noticia> noticiasFull, params string[] palavras)
        {
            IEnumerable<Noticia> noticiasRetorno = new List<Noticia>();

            if (palavras[0].StartsWith("\""))
            {
                string expressao = palavras.ToString().Replace("\"", "");
                var noticias = ListarNoticiaPorUmaPalavra(noticiasFull, expressao);
                noticiasRetorno = noticiasRetorno.Concat<Noticia>(noticias);
            }
            else
            {
                for (int i = 0; i < palavras.Length; i++)
                {
                    var noticias = ListarNoticiaPorUmaPalavra(noticiasFull, palavras[i]);
                    noticiasRetorno = noticiasRetorno.Concat<Noticia>(noticias);
                }
            }

            return noticiasRetorno.ToList<Noticia>();
        }

        private static IOrderedEnumerable<Noticia> ListarNoticiaPorUmaPalavra(IList<Noticia> noticiasFull, string expressao)
        {
            var noticias = (from c in noticiasFull
                            where
                                 c.PalavraChave.Any<PalavraChave>(x => x.Palavra.Contains(expressao)) ||
                                 c.Titulo.Contains(expressao) ||
                                 c.SubTitulo.Contains(expressao) ||
                                 c.TextoNoticia.Contains(expressao)
                            orderby c.PublicadoEm descending
                            select c);
            return noticias;
        }
    }
}
